package structures;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Supplier;


public class SingletonUtil {
    private static final Map<Object, Object> singletons = new ConcurrentHashMap<>();

    @SuppressWarnings("unchecked")
    public static <T> T singleton(Object lock, Supplier<? extends T> supplier) {
        if (lock == null) throw new IllegalArgumentException("lock is null!");
        if (!singletons.containsKey(lock)) {
            synchronized (lock) {
                if (!singletons.containsKey(lock)) {
                    singletons.put(lock, supplier.get());
                }
            }
        }
        return (T) singletons.get(lock);
    }

    public static void check(Object lock, RuntimeException throwable)  {
        synchronized (lock) {
            if (singletons.containsKey(lock)) throw throwable;
        }
    }
}
